package com.lsq.baseadmin.modules.maintenance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsq.baseadmin.common.enums.SwitchEnum;
import com.lsq.baseadmin.modules.maintenance.entity.Menu;
import com.lsq.baseadmin.modules.maintenance.mapper.MenuMapper;
import com.lsq.baseadmin.modules.maintenance.service.MenuService;
import com.lsq.baseadmin.modules.manage.utils.MenuTreeUtil;
import com.lsq.baseadmin.modules.maintenance.vo.MenuVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lsq
 * @since 2020-10-23
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    private MenuMapper menuMapper;
    @Resource
    public void setMenuMapper(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Menu menu) {
        baseMapper.updateById(menu);
        disableChildren(menu);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(Menu menu) {
        baseMapper.updateById(menu);
        disableChildren(menu);
    }

    @Override
    public List<MenuVo> myMenuTree(int userId) {
        List<Menu> menus = menuMapper.myMenus(userId);
        return MenuTreeUtil.buildTree(menus);
    }

    @Override
    public List<Menu> myMenus(int userId) {
        return menuMapper.myMenus(userId);
    }

    @Override
    public List<Menu> list(Menu menu) {
        QueryWrapper<Menu> wrapper = createWrapper(menu);
        return baseMapper.selectList(wrapper);
    }

    private void disableChildren(Menu menu) {
        // 如果是禁用， 要把其子部门全都禁用
        if (SwitchEnum.DISABLE.getValue().equals(menu.getStatus())) {
            Menu child = new Menu();
            child.setStatus(SwitchEnum.DISABLE.getValue());
            QueryWrapper<Menu> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", menu.getId());
            baseMapper.update(child, wrapper);
        }
    }
    private QueryWrapper<Menu> createWrapper(Menu menu) {
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        if(null == menu) {
            return wrapper;
        }

        if(StringUtils.hasText(menu.getName())) {
            wrapper.like("name", menu.getName());
        }
        if(StringUtils.hasText(menu.getPath())) {
            wrapper.like("path", menu.getPath());
        }

        return wrapper;
    }
}
